package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.domain.*;
import cn.wolfcode.luowowo.query.StrategyQuery;
import cn.wolfcode.luowowo.repository.StrategyRepository;
import cn.wolfcode.luowowo.service.IDestinationService;
import cn.wolfcode.luowowo.service.IStrategyService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
//@Transactional mongodb事务必须复制集方式
public class StrategyServiceImpl implements IStrategyService {

    //Spring-boot集成redis持久化数据库
    @Autowired
    private StrategyRepository repository;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyCatalogServiceImpl strategyCatalogService;

    @Autowired
    private StrategyThemeServiceImpl strategyThemeService;

    @Autowired
    private IDestinationService destinationService;

    @Override
    public void save(Strategy strategy) {

        strategy.setId(null);
        repository.save(strategy);
    }

    @Override
    public void delete(String id) {

        repository.deleteById(id);
    }

    @Override
    public void update(Strategy strategy) {

        repository.save(strategy);
    }

    @Override
    public Strategy get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> listAll() {
        return repository.findAll();
    }


    // 攻略列表更新/添加
    @Override
    public void saveOrUpdate(Strategy strategy) {

        //解决后台:冗余字段的维护(数据库数据丢失)

        // 目的地的id(添加操作)
        StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
        strategy.setDestId(catalog.getDestId());

        // 目的地的name(添加操作)
        strategy.setDestName(catalog.getDestName());

        // 主题名称(添加操作)
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());

        // 分类名称(添加操作)
        strategy.setCatalogName(catalog.getName());
        // 是否国外
        //中国>>广东>>广州(添加操作)
        List<Destination> toasts = destinationService.queryToasts(catalog.getDestId());
        if(toasts !=null && toasts.size()>0){
            Destination destination = toasts.get(0);
            if("中国".equals(destination.getName())){
                // 国内(添加操作)
                strategy.setIsabroad(Strategy.ABROAD_NO);
            }else {
                // 国外(添加操作)
                strategy.setIsabroad(Strategy.ABROAD_YES);
            }
        }

        if(StringUtils.hasLength(strategy.getId())){
            // 查询(编辑操作)
            Strategy temp = this.get(strategy.getId());
            // 替换(编辑操作)
            strategy.setCreateTime(temp.getCreateTime());
            strategy.setViewnum(temp.getViewnum());
            strategy.setReplynum(temp.getReplynum());
            strategy.setSharenum(temp.getSharenum());
            strategy.setThumbsupnum(temp.getThumbsupnum());
            strategy.setFavornum(temp.getFavornum());
            // 更新(编辑操作)
            this.update(strategy);
        }else{
            // 保存(添加操作)
            strategy.setCreateTime(new Date());
            this.save(strategy);
        }
    }

    // 下架按钮(实际是修改状态)
    @Override
    public void changeState(String id, int state) {
        // 部分更新字段
        //两种方式:1查询.2.替换3更新(方式一)
        // update table set xx=aa
        // db.table.update({...},{$set:{xx:aa}})
        //方式二:
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("state",state);
        template.updateMulti(query,update,Strategy.class);

    }

    // 通过分类id查询攻略集合
    @Override
    public List<Strategy> queryCatalogId(String id) {

        return repository.findByCatalogId(id);
    }

    // 点击量前三的攻略文章
    @Override
    public List<Strategy> queryViewnumTop3(String destId) {

        // 1.目的地id必须指定

        // 2.点击量倒序
        // 3.截取前面3个
        Pageable pageable = PageRequest.of(0,3, Sort.Direction.DESC,"viewnum");
        List<Strategy> list = repository.findByDestId(destId,pageable);
        return list;
    }

    // vo的持久化更新
    @Override
    public void updateStrategyStatisVo(StrategyStatisVO vo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));
        Update update = new Update();

        update.set("viewnum",vo.getViewnum());
        update.set("replynum",vo.getReplynum());
        update.set("favornum",vo.getFavornum());
        update.set("sharenum",vo.getSharenum());
        update.set("thumbsupnum",vo.getThumbsupnum());
        template.updateMulti(query,update,Strategy.class);
    }




    // 通过目的地名称查询攻略
    @Override
    public List<Strategy> queryByDestName(String destName) {
        return repository.findByDestName(destName);
    }
    // 攻略分页查询

    @Override
    public Page<Strategy> query(StrategyQuery qo) {

        Query query = new Query();

        // 用于查询主题
        if(StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }


        // 目的地页面查看全部按钮:
        if(StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,
                qo.getPageSize(), Sort.Direction.ASC,"_id");

        return DBHelper.query(template,Strategy.class,query,pageable);
    }
}
